package com.fesine.batch.controller;

import com.fesine.batch.model.BatchSchedulePo;
import com.fesine.batch.service.BatchScheduleService;
import com.fesine.commons.util.ConvertUtils;
import com.fesine.commons.util.MyStringUtils;
import com.fesine.commons.util.ResponseUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/2/27 21:59
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/2/27 21:59
 */
@Controller
@RequestMapping("/batchSchedule")
public class BatchScheduleController {
    protected static final Logger logger = LoggerFactory.getLogger(BatchScheduleController.class);

    @Autowired
    private BatchScheduleService batchScheduleService;

    public static final String[] dateFormat = {"yyyy-MM-dd"};


    @RequestMapping("/listPage")
    public void listPage(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        logger.debug("------>接受分页查询请求:");
        Map<String, Object> map;
        try {
            int offset = Integer.parseInt(request.getParameter("start"));
            int pageSize = Integer.parseInt(request.getParameter("limit"));
            String groupId = request.getParameter("groupId");
            String statStr = request.getParameter("status");
            BatchSchedulePo bs = new BatchSchedulePo();
            if (StringUtils.isNotBlank(groupId))
                bs.setGroupId(groupId);
            if (StringUtils.isNotBlank(statStr))
                bs.setStatus(Byte.valueOf(statStr));
            long count = batchScheduleService.count(bs);
            List<BatchSchedulePo> list = batchScheduleService.listPage(bs,
                    ConvertUtils.offsetToPageNum(offset, pageSize), pageSize);
            map = new HashedMap();
            map.put("count", count);
            map.put("list", list);
        } catch (NumberFormatException e) {
            logger.error("",e);
            throw e;
        }
        ResponseUtils.outPut(response, map);
    }

    @RequestMapping("/query")
    public void query(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        logger.debug("------>接受参数查询请求:");
        long count = 0;
        List<BatchSchedulePo> list = null;
        Map<String, Object> map = new HashedMap();
        try {
            int pageNum = Integer.parseInt(request.getParameter("pageNum"));
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            String groupId = request.getParameter("groupId");
            byte status = Byte.valueOf(request.getParameter("status"));
            BatchSchedulePo bs = new BatchSchedulePo();
            if (StringUtils.isNotBlank(groupId))
                bs.setGroupId(groupId);
            bs.setStatus(status);
            count = batchScheduleService.count(bs);
            list = batchScheduleService.listLike(bs, pageNum, pageSize);
        } catch (NumberFormatException e) {
            logger.error("", e);
            throw e;
        }
        map.put("count", count);
        map.put("list", list);
        ResponseUtils.outPut(response, map);
    }

    @RequestMapping("/addSchedule")
    public void addSchedule(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        logger.debug("------>增加定时任务操作");
        String id = request.getParameter("id");
        String groupId = request.getParameter("groupId");
        String cronExpression = request.getParameter("cronExpression");
        String startTime = request.getParameter("startTime");
        String stopTime = request.getParameter("stopTime");
        String ipAddr = request.getParameter("ipAddr");
        String status = request.getParameter("status");
        String quartzJobClass = request.getParameter("quartzJobClass");
        BatchSchedulePo bs = new BatchSchedulePo();
        Map<String, Object> map = new HashedMap();
        if (StringUtils.isBlank(id) || StringUtils.isBlank(groupId)) {
            map.put("success", false);
            map.put("msg", "id或者groupId为空!");
        } else {
            bs.setId(id);
            //新增操作
            batchScheduleService.delete(bs);
            try {
                bs = new BatchSchedulePo();
                bs.setId(id);
                bs.setGroupId(groupId);
                bs.setCronExpression(cronExpression);
                if (StringUtils.isNotBlank(startTime))
                    bs.setStartTime(DateUtils.parseDate(startTime, dateFormat));
                if (StringUtils.isNotBlank(stopTime))
                    bs.setStopTime(DateUtils.parseDate(stopTime, dateFormat));
                bs.setIpAddr(ipAddr);
                bs.setStatus(Byte.valueOf(status));
                bs.setQuartzJobClass(quartzJobClass);
                batchScheduleService.add(bs);
                map.put("success", true);
                map.put("msg", "操作成功！");
            } catch (Exception e) {
                map.put("success", false);
                map.put("msg", "操作失败!");
                logger.error("", e);
                throw e;
            }
        }
        ResponseUtils.outPut(response, map);
    }

    @RequestMapping("/updateStatus")
    public void updateStatus(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        String id = request.getParameter("id");
        String groupId = request.getParameter("groupId");
        String status = request.getParameter("status");
        logger.debug("------>接受更新状态请求ID:" + id);
        if (status.equals("1")) {
            status = "0";
        } else if (status.equals("0")) {
            status = "1";
        }
        BatchSchedulePo bs = new BatchSchedulePo();
        bs.setId(id);
        bs.setGroupId(groupId);
        bs.setStatus(Byte.valueOf(status));
        Map<String, Object> map = new HashedMap();
        try {
            batchScheduleService.update(bs);
            map.put("success", true);
            map.put("msg", "操作成功！");
        } catch (Exception e) {
            logger.error("", e);
            map.put("success", false);
            map.put("msg", "操作失败！");
        }
        ResponseUtils.outPut(response, map);
    }

    @RequestMapping("/deleteSchedule")
    public void deleteSchedule(HttpServletRequest request, HttpServletResponse response) throws
            Exception {
        String ids = request.getParameter("ids");
        ids = MyStringUtils.replaceQuotes(ids);
        logger.debug("------>接受删除操作请求ID:" + ids);
        Map<String, Object> map = new HashedMap();
        try {
            if (StringUtils.isNotBlank(ids)) {
                String[] idArr = ids.split(",");
                for (String id : idArr) {
                    BatchSchedulePo bs = new BatchSchedulePo();
                    bs.setId(id);
                    batchScheduleService.delete(bs);
                }
            }
            map.put("success", true);
            map.put("msg", "操作成功！");
        } catch (Exception e) {
            logger.error("", e);
            map.put("success", false);
            map.put("msg", "操作失败！");
        }
        ResponseUtils.outPut(response, map);
    }

}
